package net.esj.basic.utils.view;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public final class HtmlUtils {
	
	/**
	 * 格式化textarea
	 * @param str
	 * @return
	 */
	public static final String formateTextarea(String str){
		return str.replaceAll("\r\n", "<br>").replaceAll("\n", "<br>").replaceAll(" ", "&nbsp;").replaceAll("\t", "&nbsp;");
	}
	
	/**
	 * 格式化数字
	 * @param number 
	 * @param accurate 小数点后位数
	 * @return
	 */
	public static final String formateNumber(Double number,int accurate){
		String str = number.toString();
		if(str.indexOf(".")>=0){
			return str.substring(0, str.indexOf(".")+accurate+1);
		}else{
			return str;
		}
	}
	
	/**
	 * URL补全
	 * @param url
	 * @return
	 */
	public static final String completeURL(String url,boolean isSafe){
		if(isSafe){
			if(!url.startsWith("https://")){
				url ="https://"+url;
			}
		}else{
			if(!url.startsWith("http://")){
				url ="http://"+url;
			}
		}
		return url;
	}
	
	public static final String completeURL(String url){
		return completeURL(url, false);
	}
	
	public static final ByteArrayOutputStream readPageToStream(String path,String charset ,ServletContext sc,HttpServletRequest req, HttpServletResponse resp){
		RequestDispatcher rd = sc.getRequestDispatcher(path);

		final ByteArrayOutputStream os = new ByteArrayOutputStream();
		final ServletOutputStream stream = new ServletOutputStream() {
			public void write(byte[] data, int offset, int length) {
				os.write(data, offset, length);
			}

			public void write(int b) throws IOException {
				os.write(b);
			}
		};

		final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os));
		
		HttpServletResponse rep = new HttpServletResponseWrapper(resp) {
			public ServletOutputStream getOutputStream() {
				return stream;
			}

			public PrintWriter getWriter() {
				return pw;
			}
		};
		try {
			rd.include(req, rep);
			pw.flush();
			return os;
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 
	 * 基本功能：过滤指定标签
	 * <p>
	 * 
	 * @param str
	 * @param tag
	 *            指定标签
	 * @return String
	 */
	public static String fiterHtmlTag(String str, String tag) {
		//String regxp = "<\\s*" + tag + "\\s+([^>]*)\\s*>";
//		String regxp = "<"+tag.trim()+"[^>]*?>[\\s\\S]*?<\\/"+tag.trim()+">";
		String regxp = "<"+tag.trim()+"[^>]*?>";
		String regxpEnd = "<\\/"+tag.trim()+"[^>]*?>";
		
		Pattern pattern = Pattern.compile(regxp, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		boolean result1 = matcher.find();
		while (result1) {
			matcher.appendReplacement(sb, "");
			result1 = matcher.find();
		}
		matcher.appendTail(sb);
		
		pattern = Pattern.compile(regxpEnd, Pattern.CASE_INSENSITIVE);
		matcher = pattern.matcher(sb.toString());
		StringBuffer sb2 = new StringBuffer();
		boolean result2 = matcher.find();
		while (result2) {
			matcher.appendReplacement(sb2, "");
			result2 = matcher.find();
		}
		matcher.appendTail(sb2);
		return sb2.toString();
	}

	/**
	 * 
	 * 基本功能：替换指定的标签
	 * <p>
	 * 
	 * @param str
	 * @param beforeTag
	 *            要替换的标签
	 * @param tagAttrib
	 *            要替换的标签属性值
	 * @param startTag
	 *            新标签开始标记
	 * @param endTag
	 *            新标签结束标记
	 * @return String
	 * @如：替换img标签的src属性值为[img]属性值[/img]
	 */
	public static String replaceHtmlTag(String str, String beforeTag,
			String tagAttrib, String startTag, String endTag) {
		String regxpForTag = "<\\s*" + beforeTag + "\\s+([^>]*)\\s*>";
		String regxpForTagAttrib = tagAttrib + "=\"([^\"]+)\"";
		Pattern patternForTag = Pattern.compile(regxpForTag);
		Pattern patternForAttrib = Pattern.compile(regxpForTagAttrib);
		Matcher matcherForTag = patternForTag.matcher(str);
		StringBuffer sb = new StringBuffer();
		boolean result = matcherForTag.find();
		while (result) {
			StringBuffer sbreplace = new StringBuffer();
			Matcher matcherForAttrib = patternForAttrib.matcher(matcherForTag
					.group(1));
			if (matcherForAttrib.find()) {
				matcherForAttrib.appendReplacement(sbreplace, startTag
						+ matcherForAttrib.group(1) + endTag);
			}
			matcherForTag.appendReplacement(sb, sbreplace.toString());
			result = matcherForTag.find();
		}
		matcherForTag.appendTail(sb);
		return sb.toString();
	}
	
}
